package main

import (
	"github.com/nacos-group/nacos-sdk-go/common/logger"
	"log"
	"os"
	"strconv"
	"task-job/src/bean"
	"task-job/src/httpUtils"

	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"github.com/robfig/cron"
	"gopkg.in/yaml.v2"
)

func main() {
	log.Println("task start===================+>")
	ch := make(chan int)
	ch <- 1
}

var cronList = make([]*cron.Cron, 0)

var contentNacos bean.ContentNacos
var IpAddr string = "127.0.0.1"
var Port uint64 = 8848
var DataId string = ""
var Group string = "DEFAULT_GROUP"
var NamespaceId string ="80eca26c-8de9-42b4-8c18-913722792fa5"

func getPort(str string) (uint64, error) {
	num, err := strconv.ParseUint(str, 10, 64)
	if err != nil {
		log.Println("转换失败,请输入正确端口号")
		return Port, err
	}
	uint64Num := uint64(num)
	return uint64Num, err
}
func initParam(value interface{}, int1 int) interface{} {
	if len(os.Args) > int1 {
		return os.Args[int1]
	}
	return value
}

func init() {
	if len(os.Args) > 1 {
		IpAddr = initParam(IpAddr, 1).(string)
		NamespaceId = initParam(NamespaceId, 2).(string)
		DataId = initParam(DataId, 3).(string)
		Group = initParam(Group, 4).(string)
		Port, _ = getPort(initParam(strconv.FormatUint(Port, 10), 5).(string))
	}
	sc := []constant.ServerConfig{{
		IpAddr: IpAddr,
		Port:   Port,
	}}
	cc := constant.ClientConfig{
		NamespaceId:         NamespaceId, // 如果需要支持多namespace，我们可以场景多个client,它们有不同的NamespaceId。当namespace是public时，此处填空字符串。
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "log",
		CacheDir:            "cache",
		LogLevel:            "debug",
	}

	configClient, err := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": sc,
		"clientConfig":  cc,
	})
	if err != nil {
		log.Println(err.Error())
	}

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: DataId,
		Group:  Group,
	})

	if err != nil {
		log.Println(err.Error())
	}
	//fmt.Println(content) //字符串 - yaml
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: DataId,
		Group:  Group,
		OnChange: func(namespace, group, dataId, data string) {
			log.Println("配置文件发生了变化...")
			log.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
			SetConfig(data)
		},
	})
	SetConfig(content)
}

func SetConfig(content string) {
	log.Println(content)
	err := yaml.Unmarshal([]byte(content), &contentNacos)
	if err != nil {
		log.Println(err)
	}
	log.Println("%v", contentNacos)
	stopJob()
	initStartJob(contentNacos)
}

func initStartJob(contentNacos bean.ContentNacos) {
	log.Println("任务长度:", len(contentNacos.TaskBean.JobBeans))
	for i, value := range contentNacos.TaskBean.JobBeans {
		isOpen := value.IsOpen //cron表达式，每秒一次
		log.Println("isOpen:", isOpen)
		if isOpen == false {
			continue
		}
		c := cron.New() //精确到秒
		//定时任务
		spec := value.TaskTime //cron表达式，每秒一次
		runCallback := bean.RunCallback{
			OnEvent:  handleEvent,
			JobBeans: value,
		}
		err := c.AddJob(spec, runCallback)
		if err != nil {
			log.Println(i, value, "加载失败", err)
		} else {
			log.Println(i, value, "加载成功", err)
		}
		cronList = append(cronList, c)
	}
	log.Println("=====>>>长度", len(cronList))
	for _, cron := range cronList {
		go cron.Start()
	}
}

func stopJob() {
	for _, cron := range cronList {
		go cron.Stop()
	}
	cronList = make([]*cron.Cron, 0)
}

// 事件处理函数
func handleEvent(g bean.JobBeans) {
	logger.Info(g.Url, g.Param)
	post, err := httpUtils.HttpPost(g.Url, g.Param)
	if err != nil {
		str := err.Error()
		logger.Error("=====>请求报错：", g.Url, str)
	}

	logger.Info("====>请求结果：", g.Url, post)

}
